package com.dp.voucher.service.impl;

import com.dp.common.domain.dto.Result;
import com.dp.common.utils.UserHolder;
import com.dp.voucher.domain.po.VoucherOrder;
import com.dp.voucher.mapper.VoucherOrderMapper;
import com.dp.voucher.service.ISeckillVoucherService;
import com.dp.voucher.service.IVoucherOrderService;
import com.dp.voucher.utils.RedisIdWorker;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;

@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService iSeckillVoucherService;
    @Resource
    private RedisIdWorker redisIdWorker;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;
//    @Autowired
//    private KafkaTemplate<String, String> kafkaTemplate;

    // 加载seckill.lua脚本-使用Redis来优化用户下单的逻辑
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    // 注入自身获取代理对象
    @Autowired
    private IVoucherOrderService proxy;

    @Override
    public Result seckillVoucher(Long voucherId) {
        // 获取用户ID
        Long userId = UserHolder.getUser().getId();
        // 1. 执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString());
        // 2. 判断结果是否为0，0是有购买资格的
        int r = result.intValue();
        if (r != 0) {
            // 2.1 不为0-没有购买资格
            return Result.fail(r == 1 ? "库存不足" : "不能重复下单");
        }
        // 2.2 0-有购买资格，将下单的信息保存到Kafka
        long orderId = redisIdWorker.nextId("order");
        // 封装信息
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId); // 代金券ID

        // 使用 Jackson 把 VoucherOrder 对象转为 JSON 字符串
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String jsonVoucherOrder = objectMapper.writeValueAsString(voucherOrder);
            // 发送 JSON 字符串到 Kafka
//            ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send("voucher-order-topic", jsonVoucherOrder);
//            future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
//                @Override
//                public void onFailure(Throwable ex) {
//                    log.error("Failed to send message to Kafka: {}", ex.getMessage());
//                }
//
//                @Override
//                public void onSuccess(SendResult<String, String> result) {
//                    log.info("Message sent to Kafka successfully: {}", result.getRecordMetadata());
//                }
//            });
        } catch (Exception e) {
            log.error("Failed to convert VoucherOrder to JSON: {}", e.getMessage());
            return Result.fail("Failed to send order information to Kafka");
        }

        // 返回订单ID
        return Result.ok(orderId);
    }

    @Transactional
    public void createVoucher(VoucherOrder voucherOrder) {
        // 一人一单
        // 查询订单
        Long userId = voucherOrder.getUserId(); // 用户ID
        Long voucherId = voucherOrder.getVoucherId();
        int count = query().eq("user_id", userId)
                .eq("voucher_id", voucherId)
                .count();
        // 判断是否存在
        if (count > 0) {
            log.error("只能购买一次");
            return;
        }
        // 扣减库存-compare and swap
        boolean success = iSeckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherId)
                .gt("stock", 0) // CAS乐观锁思想-优化
                .update(); // update会触发数据库行级锁
        if (!success) {
            log.error("库存不足");
            return;
        }
        // 创建订单
        save(voucherOrder);
    }

//    @KafkaListener(topics = "voucher-order-topic")
    public void listen(String jsonVoucherOrder) {
        // 使用 Jackson 把 JSON 字符串转换回 VoucherOrder 对象
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            VoucherOrder voucherOrder = objectMapper.readValue(jsonVoucherOrder, VoucherOrder.class);
            // 获取用户ID
            Long userId = voucherOrder.getUserId();
            // 创建锁对象
            RLock lock = redissonClient.getLock("lock:order:" + userId);
            // 获取锁
            boolean isLock = lock.tryLock();
            if (!isLock) {
                log.error("不允许重复下单");
                return;
            }
            try {
                // 处理订单
                proxy.createVoucher(voucherOrder);
            } finally {
                // 释放锁
                lock.unlock();
            }
        } catch (Exception e) {
            log.error("Failed to convert JSON to VoucherOrder: {}", e.getMessage());
        }
    }
}